import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hong_vpn_new_20240626/utils/configs/text_style_config.dart';
import 'package:hong_vpn_new_20240626/utils/customs/zz_button.dart';
import 'package:hong_vpn_new_20240626/utils/utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:scan/scan.dart';

// import 'package:qr_code_scanner/qr_code_scanner.dart';

import '../../utils/configs/color_config.dart';

class ScanQRWidget extends StatefulWidget {
  const ScanQRWidget({super.key});

  @override
  State<ScanQRWidget> createState() => _ScanQRWidgetState();
}

class _ScanQRWidgetState extends State<ScanQRWidget> {
  // double get scanArea => (MediaQuery.of(context).size.width < 400 ||
  //         MediaQuery.of(context).size.height < 400)
  //     ? 250.0
  //     : 300.0;

  double get scanArea => MediaQuery.of(context).size.width * 0.8;

  Timer? timer;

  String _qrCode = "";

  _doQrCode(String code, {bool isPic = false}) {
    zzLog("message ======== $code");
    _qrCode = code;
    setState(() {});

    if (!isPic) {
      timer = Timer.periodic(const Duration(seconds: 2), (timer) {
        timer.cancel();
        if (mounted) {
          this.timer = null;
          controller.resume();
        }
      });
    }
  }

  _copyTap() {
    Clipboard.setData(ClipboardData(text: _qrCode))
        .then((value) => EasyLoading.showToast("Content copied to clipboard"));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Scan QR"),
        ),
        body: Padding(
          padding: EdgeInsets.only(top: 50.h, left: 15, right: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox(width: double.infinity),
              _buildQrView(),
              _buildActions(),
              _qrCode.isEmpty
                  ? Container()
                  : Column(
                      children: [
                        const SizedBox(height: 30),
                        Text(
                          "Qr Content",
                          style: TextStyleConfig.bold.size(18),
                        ),
                        Text(_qrCode,
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyleConfig.value),
                        const SizedBox(height: 8),
                        TextButton(
                          onPressed: () => _copyTap(),
                          style: const ButtonStyle(
                              backgroundColor:
                                  WidgetStatePropertyAll(ColorConfig.orange),
                              foregroundColor:
                                  WidgetStatePropertyAll(Colors.white)),
                          child: Text(
                            "Copy",
                            style: TextStyleConfig.bold,
                          ),
                        )
                      ],
                    )
            ],
          ),
        ));
  }

  ScanController controller = ScanController();

  Widget _buildQrView() {
    return Container(
      width: scanArea,
      height: scanArea,
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(20)),
      clipBehavior: Clip.hardEdge,
      child: ScanView(
        controller: controller,
        scanAreaScale: 1,
        scanLineColor: ColorConfig.orange,
        onCapture: (data) => _doQrCode(data),
      ),
    );
  }

  Widget _buildActions() {
    return Container(
      height: 50,
      width: scanArea,
      margin: const EdgeInsets.only(top: 20),
      clipBehavior: Clip.hardEdge,
      decoration: BoxDecoration(
          color: ColorConfig.orange, borderRadius: BorderRadius.circular(25)),
      child: Row(
        children: [
          Center(
            child: ZZButton(
              width: (scanArea - 1) * 0.5,
              mainAxisAlignment: MainAxisAlignment.center,
              image: Image.asset("assets/images/相册 1.png"),
              decoration: const BoxDecoration(color: ColorConfig.orange),
              onTap: () async {
                zzLog("tap photo");
                final imagepick = ImagePicker();
                try {
                  final XFile? photo =
                      await imagepick.pickImage(source: ImageSource.gallery);
                  zzLog(photo?.path ?? "");
                  if (photo?.path != null) {
                    EasyLoading.show(maskType: EasyLoadingMaskType.black);
                    var code = await Scan.parse(photo!.path);
                    EasyLoading.dismiss();
                    zzLog("ccccc = $code");
                    if (code == null || code.isEmpty) {
                      EasyLoading.showToast("No QR code detected");
                    } else {
                      _doQrCode(code, isPic: true);
                    }
                  } else {
                    EasyLoading.showToast("No QR code detected");
                  }
                } catch (e) {
                  EasyLoading.showToast("Failed to get picture");
                }
              },
            ),
          ),
          Container(
            width: 1,
            height: 30,
            color: Colors.white,
          ),
          ZZButton(
            width: (scanArea - 1) * 0.5,
            mainAxisAlignment: MainAxisAlignment.center,
            image: Image.asset("assets/images/手电筒.png"),
            decoration: const BoxDecoration(color: ColorConfig.orange),
            onTap: () async => controller.toggleTorchMode(),
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    if (timer != null) {
      timer?.cancel();
    }
    super.dispose();
  }
}
